#!/usr/bin/env python  
# -*- coding: utf-8 -*-  
"""  
@author: ઈ一笑ഒ 
@time: 2024/11/2 16:09  
@file: consumers.py  
@project: newenergy  
@describe: TODO  
"""
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
from asgiref.sync import async_to_sync

class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        #有客户端来向后台发送websocket连接请求时，自动触发
        #服务端允许客户端创建连接
        print("有人连接")
        self.accept()

        #获取群号
        group = self.scope['url_route']['kwargs'].get("group")
        print(group)
        #将这个客户端连接对象加入到内存
        #channel_layer.group_add这个方法默认是异步的所有需要async_to_sync转成同步
        async_to_sync(self.channel_layer.group_add)(group,self.channel_name)


     #浏览器基于websocket向后端发送数据，自动触发接收消息
    def websocket_receive(self, message):
        #获取群号
        group = self.scope['url_route']['kwargs'].get("group")
        #通知组内所有客户端，执行xx_oo方法，在此方法中可以自己定义任意功能
        async_to_sync(self.channel_layer.group_send)(group,{"type":"xx_oo","message":message})
    def xx_oo(self, event):
        text = event["message"]["text"]
        self.send(text)

    def websocket_disconnect(self, message):
        print("客户端断开连接")
        group = self.scope['url_route']['kwargs'].get("group")
        #客户端与服务器断开连接时自动触发
        async_to_sync(self.channel_layer.group_discard)(group,self.channel_name)
        raise StopConsumer()